# -*- coding: utf-8 -*-
import gtk

import layerlist
import editwindow
import layer
import action

class LevelEditorWindow(gtk.Window):
    """Main window for the level editor.
    """

    def __init__(self, width=800, height=600):
        """Creates the window.
	"""
	super(LevelEditorWindow, self).__init__()
        self.set_default_size(width, height)

        # Main vbox for menu, edit area and status bar
        contents = gtk.VBox()

        contents.pack_start(gtk.MenuBar(), False)
        contents.pack_start(self.create_toolbar(),False)
        contents.pack_start(self.edit_area(), True)
        contents.pack_start(gtk.Statusbar(), False)

        self.add(contents)

    def create_toolbar(self):
        toolbar = gtk.Toolbar()
        toolbar.set_property("toolbar-style", gtk.TOOLBAR_ICONS)

        toolbar.insert(gtk.ToolButton(gtk.STOCK_NEW), toolbar.get_n_items())
        toolbar.insert(gtk.ToolButton(gtk.STOCK_OPEN), toolbar.get_n_items())
        toolbar.insert(gtk.ToolButton(gtk.STOCK_SAVE), toolbar.get_n_items())

        return toolbar

    def edit_area(self):
        # tool_box = toolbox.ToolBox()
        class Foo:
            pass
        self.tool_box = Foo()
        self.tool_box.get_action = lambda : (action.DrawAction, (1,))

        self.layer_list = layerlist.LayerList()

        self.edit_window = editwindow.EditWindow(self.layer_list, self.tool_box)
        scroll_area = gtk.ScrolledWindow()
        scroll_area.add_with_viewport(self.edit_window)

        hbox = gtk.HBox()
        # hbox.pack_start(tool_box, False)
        hbox.pack_start(scroll_area, True)
        hbox.pack_end(self.layer_list, False)

        return hbox


class LevelEditor(object):
    """The level editor application
    """

    def __init__(self):
        """Initialize the application.
	"""
        self.register_layer_types()

	self.window = LevelEditorWindow()
        self.window.connect("delete-event", self.quit)

    def register_layer_types(self):
        """Register the existent layer types"""
        layerlist.LayerList.register_layer_type(layer.TileLayer)

    def run(self):
        """Run the level editor starting the gtk main loop.
        """
        self.window.show_all()
        gtk.main()

    def quit(self, window, event):
        """Quit the application
        """
        gtk.main_quit()


def main():
    """Run the level editor
    """
    import random
    import tileset
    from layer import TileLayer

    level_editor = LevelEditor()

    tileset = tileset.from_image("test_tileset", "hills3.png", 32)
    tile_layer = TileLayer("test", 100, 100, tileset)

    for x in range(100):
        for y in range(100):
            tile_layer._data[x][y] = random.randint(0, 20)

    level_editor.window.layer_list.add_layer(tile_layer)
    level_editor.window.edit_window.update_size()

    level_editor.run()

if __name__ == '__main__':
    main()
